package com.tencent.wxcloudrun.utils;

import cn.hutool.system.OsInfo;
import cn.hutool.system.SystemUtil;
import com.aspose.words.Document;
import com.aspose.words.FontSettings;
import com.aspose.words.FontSourceBase;
import com.aspose.words.FolderFontSource;
import com.aspose.words.SystemFontSource;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.logging.Logger;
import java.util.logging.Level;

public class AsposeUtil {

    private static License license = null;
    private static final Logger logger = Logger.getLogger(AsposeUtil.class.getName());
    private static FontSettings fontSettings = null;

    /**
     * 加载license 用于破解 不生成水印
     *
     * @author yonghaoRen
     * @date 2022/12/5 13:51
     */
    public static void getLicense() throws IOException, Exception {
        if (license != null)
            return;
        try (InputStream is = AsposeUtil.class.getClassLoader().getResourceAsStream("lib/License.xml")) {
            license = new License();
            license.setLicense(is);
        }
    }

    /**
     * 创建字体设置，解决中文乱码问题
     *
     * @return FontSettings 字体设置对象
     */
    private static FontSettings createFontSettings() {
        if (fontSettings != null)
            return fontSettings;
        fontSettings = FontSettings.getDefaultInstance();
        try {
            // 尝试从资源文件夹加载字体
            String fontPath = extractFontToTemp();

            // 设置系统字体源和自定义字体文件夹
            // 在微信云托管环境中，字体可能安装在不同路径下
            FontSourceBase[] sources = new FontSourceBase[]{
                    new SystemFontSource(), // 系统字体
                    new FolderFontSource(fontPath, true) // 应用程序内嵌字体路径
            };
            fontSettings.setFontsSources(sources);
        } catch (Exception e) {
            logger.log(Level.WARNING, "无法设置自定义字体，将使用系统默认字体配置: ", e);
            // 如果无法加载内嵌字体，则使用系统默认配置
            FontSourceBase[] sources = new FontSourceBase[]{
                    new SystemFontSource()
            };
            fontSettings.setFontsSources(sources);
        }

        return fontSettings;
    }

    /**
     * 将字体文件从资源目录提取到临时目录
     *
     * @return 字体文件所在的临时目录路径
     * @throws IOException
     */
    private static String extractFontToTemp() throws IOException {
        // 获取系统临时目录
        String tempDir = System.getProperty("java.io.tmpdir");
        Path fontDir = Paths.get(tempDir, "fonts");

        // 创建字体目录
        if (!Files.exists(fontDir)) {
            Files.createDirectories(fontDir);
        }

        // 字体文件列表
        String[] fontFiles = {"simsun.ttc", "SimsunExtG.ttf", "simsunb.ttf"};
        for (String fontFile : fontFiles) {
            try (InputStream is = AsposeUtil.class.getClassLoader().getResourceAsStream("fonts/" + fontFile)) {
                if (is != null) {
                    Path targetFile = fontDir.resolve(fontFile);
                    Files.copy(is, targetFile, StandardCopyOption.REPLACE_EXISTING);
                    logger.info("成功提取字体文件: " + fontFile);
                } else {
                    logger.warning("未找到字体文件: " + fontFile);
                }
            } catch (IOException e) {
                logger.log(Level.WARNING, "无法提取字体文件: " + fontFile, e);
            }
        }

        return fontDir.toString();
    }

    /**
     * word转pdf
     *
     * @param wordPath word文件保存的路径
     * @param pdfPath  转换后pdf文件保存的路径
     * @author yonghaoRen
     * @date 2020/12/25 13:51
     */
    public static boolean wordToPdf(String wordPath, String pdfPath) {
        boolean success = false;
        try {
            getLicense();
            File file = new File(pdfPath);
            FileOutputStream os = new FileOutputStream(file);

            // 获取字体配置，解决中文乱码问题
            FontSettings fontSettings = createFontSettings();

            Document doc = new Document(wordPath);
            // 应用字体设置到文档
            doc.setFontSettings(fontSettings);
            doc.save(os, SaveFormat.PDF);
            success = true;
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Word转PDF过程中发生错误: ", e);
        }
        return success;
    }
}